package cfengMiddleware.server.rabbitmq.producer;

import cfengMiddleware.server.rabbitmq.entity.MessageEntity;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author Cfeng
 * @date 2022/9/16
 */

@Component
@RequiredArgsConstructor
@Slf4j
public class FanoutPublisher {

    private final RabbitTemplate rabbitTemplate;

    private final ObjectMapper objectMapper;

    private final Environment environment;

    public void sendMsg(MessageEntity messageEntity) throws Exception {
        if(!Objects.isNull(messageEntity)) {
            try {
                rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());

                //这里只需要指定交换机，不需要给出Routing key
                rabbitTemplate.setExchange(Objects.requireNonNull(environment.getProperty("spring.rabbitmq.exchange-fanout-name")));
                //创建消息Message，转换
                Message message = MessageBuilder.withBody(objectMapper.writeValueAsBytes(messageEntity)).build();
                rabbitTemplate.convertAndSend(message);
//                rabbitTemplate.convertAndSend(messageEntity, message -> {
//                    MessageProperties properties = message.getMessageProperties();
//                    properties.setHeader(AbstractJavaTypeMapper.DEFAULT_KEY_CLASSID_FIELD_NAME,MessageEntity.class);
//                    return message;
//                });
                log.info("消息模型Fanout 生产者发送消息： {}",messageEntity);
            } catch (Exception e) {
                log.error("消息模型Fanout 生产者发送消息异常： {}", messageEntity,e.fillInStackTrace());
            }
        }
    }
}
